﻿Namespace My

    ' The following events are available for MyApplication:
    ' 
    ' Startup: Raised when the application starts, before the startup form is created.
    ' Shutdown: Raised after all application forms are closed.  This event is not raised if the application terminates abnormally.
    ' UnhandledException: Raised if the application encounters an unhandled exception.
    ' StartupNextInstance: Raised when launching a single-instance application and the application is already active. 
    ' NetworkAvailabilityChanged: Raised when the network connection is connected or disconnected.
    Partial Friend Class MyApplication
        Private LibPath As String = ""
        Private LogFile As New Logger

        Private Sub MyApplication_Shutdown(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Shutdown
            LogFile.Close()
        End Sub
        Private Sub AppStart(ByVal sender As Object, ByVal e As Microsoft.VisualBasic.ApplicationServices.StartupEventArgs) Handles Me.Startup
            If My.Computer.Registry.LocalMachine.OpenSubKey("SOFTWARE\UCS\Ide") IsNot Nothing Then
                LibPath = My.Computer.Registry.GetValue("HKEY_LOCAL_MACHINE\SOFTWARE\UCS\Ide", "LibPath", "")
            Else
                Dim X As New SystemPaths
                If X.ShowDialog = DialogResult.OK Then
                    LibPath = My.Computer.Registry.GetValue("HKEY_LOCAL_MACHINE\SOFTWARE\UCS\Ide", "LibPath", "")
                Else
                    End
                End If
            End If
            AddHandler AppDomain.CurrentDomain.AssemblyResolve, AddressOf ResolveAssemblies
        End Sub
        Private Function ResolveAssemblies(ByVal sender As Object, ByVal e As System.ResolveEventArgs) As Reflection.Assembly
            Dim desiredAssembly = New Reflection.AssemblyName(e.Name)
            Dim Filename As String = IO.Path.Combine(LibPath, desiredAssembly.Name & ".Dll")
            If IO.File.Exists(Filename) Then
                LogFile.Write("Loading Dll : " & Filename)
                Return Reflection.Assembly.LoadFrom(Filename)
            Else
                Dim Pr As String = "File or Folder not found : " & Filename
                LogFile.Write(Pr)
                MsgBox(Pr, MsgBoxStyle.Critical, "Error!")
                Dim X As New SystemPaths
                If X.ShowDialog = DialogResult.OK Then
                    LibPath = My.Computer.Registry.GetValue("HKEY_LOCAL_MACHINE\SOFTWARE\UCS\Ide", "LibPath", "")
                End If
                MsgBox("Please restart IDE", MsgBoxStyle.Information, "Error!")
                End
            End If
            Return Nothing
        End Function
    End Class

End Namespace

